#!/bin/bash
# macOS 网络配置完整备份脚本（修复版）
# 使用方法: chmod +x fixed_network_backup.sh && ./fixed_network_backup.sh

# 创建备份目录
BASE_BACKUP_DIR="/Users/m/Downloads/netWorkBackUp"
BACKUP_DIR="$BASE_BACKUP_DIR/netWork-backup-$(date +%y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"

echo "开始备份macOS网络配置（修复版）..."
echo "备份目录: $BACKUP_DIR"

# 1. 备份网络接口配置
echo "1. 备份网络接口配置..."
ifconfig -a > "$BACKUP_DIR/ifconfig.txt"
networksetup -listallnetworkservices > "$BACKUP_DIR/network_services.txt"

# 备份每个网络服务的详细配置
networksetup -listallnetworkservices | tail -n +2 | while read service; do
    if [ ! -z "$service" ]; then
        echo "备份服务: $service"
        networksetup -getinfo "$service" > "$BACKUP_DIR/service_${service// /_}.txt"
        
        # 备份每个服务的代理设置
        echo "备份 $service 的代理设置..."
        networksetup -getwebproxy "$service" > "$BACKUP_DIR/proxy_web_${service// /_}.txt" 2>/dev/null
        networksetup -getsecurewebproxy "$service" > "$BACKUP_DIR/proxy_secure_${service// /_}.txt" 2>/dev/null
        networksetup -getsocksfirewallproxy "$service" > "$BACKUP_DIR/proxy_socks_${service// /_}.txt" 2>/dev/null
        networksetup -getftpproxy "$service" > "$BACKUP_DIR/proxy_ftp_${service// /_}.txt" 2>/dev/null
        networksetup -getproxybypassdomains "$service" > "$BACKUP_DIR/proxy_bypass_${service// /_}.txt" 2>/dev/null
    fi
done

# 2. 备份DNS配置
echo "2. 备份DNS配置..."
scutil --dns > "$BACKUP_DIR/dns_config.txt"
cat /etc/resolv.conf > "$BACKUP_DIR/resolv_conf.txt"

# 备份每个服务的DNS设置
networksetup -listallnetworkservices | tail -n +2 | while read service; do
    if [ ! -z "$service" ]; then
        networksetup -getdnsservers "$service" > "$BACKUP_DIR/dns_${service// /_}.txt" 2>/dev/null
        networksetup -getsearchdomains "$service" > "$BACKUP_DIR/search_domains_${service// /_}.txt" 2>/dev/null
    fi
done

# 3. 备份路由表
echo "3. 备份路由表..."
netstat -rn > "$BACKUP_DIR/routing_table.txt"
arp -a > "$BACKUP_DIR/arp_table.txt"

# 4. 备份防火墙设置
echo "4. 备份防火墙设置..."
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate > "$BACKUP_DIR/firewall_state.txt" 2>/dev/null
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --listapps > "$BACKUP_DIR/firewall_rules.txt" 2>/dev/null

# 5. 备份hosts文件
echo "5. 备份hosts文件..."
cp /etc/hosts "$BACKUP_DIR/hosts.txt"

# 6. 备份网络偏好设置（修复路径）
echo "6. 备份网络偏好设置..."
if [ -d "/Library/Preferences/SystemConfiguration" ]; then
    echo "备份系统网络配置文件..."
    sudo cp -r "/Library/Preferences/SystemConfiguration" "$BACKUP_DIR/" 2>/dev/null
    sudo chown -R $(whoami) "$BACKUP_DIR/SystemConfiguration" 2>/dev/null
else
    echo "⚠️  SystemConfiguration目录不存在"
fi

# 7. 备份网络位置信息
echo "7. 备份网络位置信息..."
networksetup -listlocations > "$BACKUP_DIR/network_locations.txt"
networksetup -getcurrentlocation > "$BACKUP_DIR/current_location.txt"

# 8. 记录Redis服务器信息
echo "8. 记录Redis服务器信息..."
REDIS_HOST="test-redis.oyumwu.clustercfg.apne1.cache.amazonaws.com"
cat > "$BACKUP_DIR/redis_server_info.txt" << EOF
目标Redis服务器: $REDIS_HOST
记录时间: $(date)

注意: 此Redis服务器需要公钥认证，请先配置本地公钥后联系运维添加到白名单

连接测试命令（配置公钥后使用）:
ping $REDIS_HOST
nc -z -v $REDIS_HOST 6379
EOF

# 9. 创建完整的恢复脚本
echo "9. 创建完整的恢复脚本..."
cat > "$BACKUP_DIR/restore.sh" << 'EOF'
#!/bin/bash
# macOS 网络配置完整恢复脚本

echo "开始恢复网络配置..."

# 检查是否以管理员权限运行
if [ "$EUID" -ne 0 ]; then
    echo "此脚本需要管理员权限，请使用 sudo ./restore.sh"
    exit 1
fi

# 1. 恢复hosts文件
if [ -f "hosts.txt" ]; then
    echo "恢复hosts文件..."
    cp hosts.txt /etc/hosts
    echo "✅ hosts文件已恢复"
else
    echo "❌ 找不到hosts.txt文件"
fi

# 2. 恢复网络偏好设置
if [ -d "SystemConfiguration" ]; then
    echo "恢复网络偏好设置..."
    # 备份当前配置
    cp -r /Library/Preferences/SystemConfiguration /Library/Preferences/SystemConfiguration.backup.$(date +%Y%m%d_%H%M%S)
    
    # 恢复配置
    cp -r SystemConfiguration/* /Library/Preferences/SystemConfiguration/
    echo "✅ 网络偏好设置已恢复"
else
    echo "❌ 找不到SystemConfiguration目录"
fi

# 3. 恢复代理设置
echo "恢复代理设置..."
for proxy_file in proxy_web_*.txt; do
    if [ -f "$proxy_file" ]; then
        # 从文件名提取服务名
        service_name=$(echo "$proxy_file" | sed 's/proxy_web_//' | sed 's/.txt$//' | sed 's/_/ /g')
        echo "恢复 $service_name 的HTTP代理..."
        
        # 解析代理设置
        if grep -q "Enabled: Yes" "$proxy_file"; then
            server=$(grep "Server:" "$proxy_file" | cut -d' ' -f2)
            port=$(grep "Port:" "$proxy_file" | cut -d' ' -f2)
            if [ ! -z "$server" ] && [ ! -z "$port" ]; then
                networksetup -setwebproxy "$service_name" "$server" "$port"
                echo "  设置HTTP代理: $server:$port"
            fi
        else
            networksetup -setwebproxystate "$service_name" off
            echo "  禁用HTTP代理"
        fi
    fi
done

for proxy_file in proxy_secure_*.txt; do
    if [ -f "$proxy_file" ]; then
        service_name=$(echo "$proxy_file" | sed 's/proxy_secure_//' | sed 's/.txt$//' | sed 's/_/ /g')
        echo "恢复 $service_name 的HTTPS代理..."
        
        if grep -q "Enabled: Yes" "$proxy_file"; then
            server=$(grep "Server:" "$proxy_file" | cut -d' ' -f2)
            port=$(grep "Port:" "$proxy_file" | cut -d' ' -f2)
            if [ ! -z "$server" ] && [ ! -z "$port" ]; then
                networksetup -setsecurewebproxy "$service_name" "$server" "$port"
                echo "  设置HTTPS代理: $server:$port"
            fi
        else
            networksetup -setsecurewebproxystate "$service_name" off
            echo "  禁用HTTPS代理"
        fi
    fi
done

for proxy_file in proxy_socks_*.txt; do
    if [ -f "$proxy_file" ]; then
        service_name=$(echo "$proxy_file" | sed 's/proxy_socks_//' | sed 's/.txt$//' | sed 's/_/ /g')
        echo "恢复 $service_name 的SOCKS代理..."
        
        if grep -q "Enabled: Yes" "$proxy_file"; then
            server=$(grep "Server:" "$proxy_file" | cut -d' ' -f2)
            port=$(grep "Port:" "$proxy_file" | cut -d' ' -f2)
            if [ ! -z "$server" ] && [ ! -z "$port" ]; then
                networksetup -setsocksfirewallproxy "$service_name" "$server" "$port"
                echo "  设置SOCKS代理: $server:$port"
            fi
        else
            networksetup -setsocksfirewallproxystate "$service_name" off
            echo "  禁用SOCKS代理"
        fi
    fi
done

# 4. 重启网络服务
echo "重启网络服务..."
dscacheutil -flushcache
killall -HUP mDNSResponder

# 5. 重启网络接口
echo "重启网络接口..."
networksetup -setairportpower en0 off 2>/dev/null
sleep 2
networksetup -setairportpower en0 on 2>/dev/null

echo ""
echo "✅ 网络配置恢复完成！"
echo "建议重启系统以确保所有设置完全生效"
echo "重启后请测试网络连接和Redis服务器访问"
EOF

chmod +x "$BACKUP_DIR/restore.sh"

# 10. 创建备份验证脚本
echo "10. 创建备份验证脚本..."
cat > "$BACKUP_DIR/verify_backup.sh" << 'EOF'
#!/bin/bash
# 备份验证脚本

echo "验证备份完整性..."

# 检查必要文件
required_files=(
    "ifconfig.txt"
    "network_services.txt" 
    "dns_config.txt"
    "routing_table.txt"
    "hosts.txt"
    "redis_server_info.txt"
)

missing_files=()
for file in "${required_files[@]}"; do
    if [ ! -f "$file" ]; then
        missing_files+=("$file")
    fi
done

if [ ${#missing_files[@]} -eq 0 ]; then
    echo "✅ 所有必要文件都已备份"
else
    echo "❌ 缺少以下文件:"
    for file in "${missing_files[@]}"; do
        echo "  - $file"
    done
fi

# 检查SystemConfiguration目录
if [ -d "SystemConfiguration" ]; then
    echo "✅ SystemConfiguration目录已备份"
    echo "  包含 $(ls SystemConfiguration | wc -l) 个配置文件"
else
    echo "❌ SystemConfiguration目录未备份"
fi

# 统计代理配置文件
proxy_files=$(ls proxy_*.txt 2>/dev/null | wc -l)
echo "✅ 备份了 $proxy_files 个代理配置文件"

echo ""
echo "备份验证完成"
EOF

chmod +x "$BACKUP_DIR/verify_backup.sh"

# 11. 创建备份信息文件
echo "11. 创建备份信息文件..."
cat > "$BACKUP_DIR/backup_info.txt" << EOF
macOS 网络配置完整备份信息（修复版）
=====================================
备份时间: $(date)
备份目录: $BACKUP_DIR

备份内容:
- 网络接口配置 (ifconfig.txt)
- 网络服务配置 (network_services.txt, service_*.txt)
- DNS配置 (dns_config.txt, resolv_conf.txt, dns_*.txt)
- 路由表 (routing_table.txt, arp_table.txt)
- 代理设置 (proxy_*.txt) - 所有网络服务的完整代理配置
- 防火墙设置 (firewall_state.txt, firewall_rules.txt)
- hosts文件 (hosts.txt)
- 网络偏好设置 (SystemConfiguration/) - 系统级网络配置
- 网络位置信息 (network_locations.txt, current_location.txt)
- Redis服务器信息 (redis_server_info.txt)

恢复方法:
1. 进入备份目录: cd $BACKUP_DIR
2. 验证备份: ./verify_backup.sh
3. 运行恢复脚本: sudo ./restore.sh
4. 重启系统

验证方法:
- 运行 ./verify_backup.sh 检查备份完整性
- 恢复后使用网络监控脚本检查配置

注意事项:
- 恢复需要管理员权限 (sudo)
- 建议恢复前再次备份当前配置
- 恢复后需要重启系统
- 如果遇到问题，可以手动恢复各个配置文件
EOF

echo ""
echo "✅ 完整备份完成！"
echo "备份位置: $BACKUP_DIR"
echo "验证备份: cd $BACKUP_DIR && ./verify_backup.sh"
echo "恢复方法: cd $BACKUP_DIR && sudo ./restore.sh"
echo "备份信息: $BACKUP_DIR/backup_info.txt"
echo ""
echo "Redis服务器信息已记录: $REDIS_HOST"
echo "注意: 需要先配置公钥认证才能连接"
